package com.cn.yugan.Activity;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.yugan.Engine.Beans.UpInfo;
import com.cn.yugan.Engine.Http.AddReqCookie;
import com.cn.yugan.Engine.Json.UpInfoJson;
import com.cn.yugan.Fragment.UpinfoFragment;
import com.cn.yugan.Utils.LogUtils;
import com.cn.yugan.Utils.ToastUtils;
import com.cn.yugan.mobile.R;

import com.cn.yugan.Widget.NestedView.NestedNavLayout;
import com.cn.yugan.Widget.NestedView.NestedViewPagerIndicator;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.Picasso;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Rover on 2016/8/16 .
 * Email 357319517@qq.com
 * Up主详情页
 */
public class UpinfoActivity extends AppCompatActivity implements View.OnClickListener {

    private String[] mTitles = new String[]{"他的投稿", "他的关注"};
    private NestedViewPagerIndicator mIndicator;
    private ViewPager mViewPager;
    private NestedNavLayout mLayout;
    private UpinfoFragment[] mFragments = new UpinfoFragment[mTitles.length];
    private Button message;
    private Button mark;
    private ActionBar actionBar;
    private List<TextView> tvitems;
    private String uid;
    private Button btmark;
    private LinearLayout tagsll;
    private ImageView userimage;
    private TextView username;
    private TextView usersign;
    private UpInfo upinfo;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            actionBar.setTitle(upinfo.getUsername());
            username.setText(upinfo.getUsername());
            if (upinfo.getImg() == null||upinfo.getImg().isEmpty()||upinfo.getImg().equals("")) {
                Picasso.with(UpinfoActivity.this).load(R.mipmap.default_img).into(userimage);
            }else {
                Picasso.with(UpinfoActivity.this).load(getString(R.string.imgserverurl) + upinfo.getImg().replace("?", "!userface75?")).error(R.mipmap.default_img).into(userimage);   
            }
           
            usersign.setText(upinfo.getIntro());
            settags();
            if (upinfo.getIvote()) {
                btmark.setText("已关注");
            } else {
                btmark.setText("未关注");
            }


            ArrayList<Object> mdatas1 = new ArrayList<>();
            mdatas1.addAll(upinfo.getArticleList());
            mFragments[0].setdata(mdatas1);
            
            ArrayList<Object> mdatas2 = new ArrayList<>();
            mdatas2.addAll(upinfo.getVoteList());
            mFragments[1].setdata(mdatas2);

            super.handleMessage(msg);
        }
    };

    //设置tags
    private void settags() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String tags = upinfo.getTags();
                if (!"null".equals(tags)&&tags!=null&&tags!="") {
                    String[] tagstr = tags.split(" ");
                    LogUtils.d(tagstr[0]);
                    int count = 0;
                    for (String str : tagstr) {
                        count++;
                        final TextView textView = new TextView(UpinfoActivity.this);
                        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textView.setBackground(getResources().getDrawable(R.drawable.bg_tv_lv));
                        textView.setTextColor(Color.WHITE);
                        textView.setTextSize(10);
                        textView.setGravity(Gravity.CENTER);
                        textView.setPadding(10, 10, 10, 10);
                        String[] info = str.split(":");
                        if (count == 4) {
                            textView.setText("...");
                            break;
                        }
                        if (info[0].matches("[0-9]+")) {
                            textView.setText(info[1]);
                        } else {
                            textView.setText(info[0]);
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tagsll.addView(textView);
                            }
                        });
                    }
                }
            }
        }).start();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.actionbaroverlay);
        requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upinfo);
        
        init();
        initViews();
        initDatas();
        initEvents();
        initActionBar();
        getupinfo();
    }

    private void init() {
        Intent intent = getIntent();
        uid = intent.getStringExtra("uid");
    }


    private void initEvents() {
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                mIndicator.scroll(position, positionOffset);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void initDatas() {
        mIndicator.setTitles(mTitles);
        tvitems = mIndicator.getTvitems();
        for (int i = 0; i < mTitles.length; i++) {
//            mFragments[i] = (UpinfoFragment) UpinfoFragment.newInstance(mTitles[i],i);
            mFragments[i] = new UpinfoFragment(i);
        }
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mTitles.length;
            }

            @Override
            public Fragment getItem(int position) {
                return mFragments[position];
            }
        });
        mViewPager.setCurrentItem(0);

        for (int i = 0; i < tvitems.size(); i++) {
            final int position = i;
            tvitems.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mViewPager.setCurrentItem(position);
                }
            });
        }
    }

    private void initViews() {
        mIndicator = (NestedViewPagerIndicator) findViewById(R.id.upinfo_indicator);
        mViewPager = (ViewPager) findViewById(R.id.upinfo_vp);
        mLayout = (NestedNavLayout) findViewById(R.id.upinfo_sv);

        
        message = (Button) findViewById(R.id.nav_upinfo_message);
        mark = (Button) findViewById(R.id.nav_upinfo_mark);

        userimage = (ImageView) findViewById(R.id.nav_upinfo_userimg_img);
        username = (TextView) findViewById(R.id.nav_upinfo_username);
        usersign = (TextView) findViewById(R.id.nav_upinfo_sign);
        tagsll = (LinearLayout) findViewById(R.id.nav_upinfo_userlv);
        btmark = (Button) findViewById(R.id.nav_upinfo_mark);

        btmark.setOnClickListener(this);
        message.setOnClickListener(this);
        mark.setOnClickListener(this);
    }

    private void initActionBar() {
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        ColorDrawable bgDrawable = new ColorDrawable(getResources().getColor(R.color.tianyiblue));
        mLayout.bindingActionBar(actionBar);
        try {
            mLayout.setActionBarBgDrawable(bgDrawable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getupinfo() {
        String url = getString(R.string.serverurl) + getString(R.string.getinfos);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient(true, 80, 443);
        asyncHttpClient.addHeader("cookie", AddReqCookie.getNormalheader(this));
        RequestParams requestParams = new RequestParams();
        requestParams.put("uid", uid);
        requestParams.put("names[0]", "username");
        requestParams.put("names[1]", "img");
        requestParams.put("names[2]", "regtime");
        requestParams.put("names[3]", "tags");
        requestParams.put("names[4]", "intro");
        requestParams.put("names[5]", "ivote");
        requestParams.put("names[6][0]", "voteList");
        requestParams.put("names[6][1][0]", 1);
        requestParams.put("names[6][1][1]", 20);
        requestParams.put("names[7][0]", "articleList");
        requestParams.put("names[7][1][0]", 1);
        requestParams.put("names[7][1][1]", 20);
        asyncHttpClient.post(url, requestParams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                upinfo = UpInfoJson.json2list(bytes, uid);
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.nav_upinfo_mark:
                if ("已关注".equals(mark.getText().toString())) {
                    setivote(false);
                } else {
                    setivote(true);
                }
                //Toast.makeText(this, "Mark!", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_upinfo_message:
                Toast.makeText(this, "Message", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    /**
     * 关注逻辑
     *
     * @param vote true：关注 false:取消关注
     */
    private void setivote(boolean vote) {
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient(true, 80, 443);
        asyncHttpClient.addHeader("cookie", AddReqCookie.getNormalheader(this));
        RequestParams params = new RequestParams();
        params.put("uid", uid);
        if (vote) {
            params.put("type", "vote");
        } else {
            params.put("type", "unvote");
        }
        asyncHttpClient.post(getString(R.string.serverurl) + getString(R.string.vote), params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    String a = new String(bytes, "UTF-8");
                    LogUtils.d(a);
                    JSONObject json = new JSONObject(a);
                    boolean success = json.getBoolean("success");
                    boolean ivote = json.getJSONObject("data").getBoolean("vote");
                    if (ivote && success) {
                        ToastUtils.show(UpinfoActivity.this, "关注成功");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mark.setText("已关注");
                            }
                        });
                    } else if (!ivote && success) {
                        ToastUtils.show(UpinfoActivity.this, "已取消关注");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mark.setText("未关注");
                            }
                        });
                    } else {
                        ToastUtils.show(UpinfoActivity.this, "网络传输故障");
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                ToastUtils.show(UpinfoActivity.this, "网络传输故障");
            }
        });
    }
}
